package com.yupi.yuaiagent.agent;


import com.yupi.yuaiagent.agent.model.AgentState;
import io.micrometer.common.util.StringUtils;
import io.reactivex.Completable;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Data
public abstract class BaseAgent {

    //核心属性
    private String name;

    //提示
    private String systemPrompt;
    private String nextStepPrompt;

    //状态
    private AgentState state = AgentState.IDLE;

    //执行控制
    private int maxSteps = 10;
    private int currentStep = 0;

    //LLH
    private ChatClient chatClinent;

    //消息列表
    private List<Message> messageList = new ArrayList<>();

    /**
     * 执行代理逻辑
     * @param userPrompt 用户提示词
     * @return 执行结果
     */
    public String run(String userPrompt) {
        if (this.state != AgentState.IDLE) {
            throw new RuntimeException("Cannot run agent from state: " + this.state);
        }
        if (StringUtils.isBlank(userPrompt)) {
            throw new RuntimeException("Cannot run agent with empty user prompt");
        }

        //更改状态为运行中
        this.state = AgentState.RUNNING;

        //记录上下文（含用户的输入信息）
        messageList.add(new UserMessage(userPrompt));

        //保存结果列表
        List<String> results = new ArrayList<>();

        //执行循环
        try{
            for (int i = 0; i < maxSteps && state!=AgentState.FINISHED; i++) {
                int stepNumber = i + 1;
                currentStep = stepNumber;
                log.info("Executing step {} of {}", stepNumber, maxSteps);
                //执行步骤
                String stepResult = step();
                //记录结果
                String result = "Step: " + currentStep + ": " + stepResult;
                results.add(stepResult);
            }
            if (currentStep >= maxSteps) {
                state = AgentState.FINISHED;
                results.add("Terminated: Reached max steps("+maxSteps+")");
            }
            return String.join("\n", results);
        }catch (Exception e){
            state = AgentState.FINISHED;
            log.error("Error running agent", e);
            return "Error running agent: " + e.getMessage();
        }finally{
            //释放资源
            this.cleanUp();
        }
    }

    /**
     * 执行代理逻辑，返回sse消息
     * @param userPrompt 用户提示词
     * @return 执行结果
     */
    public SseEmitter runStream(String userPrompt) {
        //创建应该超时间间隔为5分钟的sseEmitter
        SseEmitter sseEmitter = new SseEmitter(5 * 60 * 1000L);
        //使用线程异步处理，避免阻塞主线程
        CompletableFuture.runAsync(()-> {
            //1.基础检验
            try {
                if (this.state != AgentState.IDLE) {
                    sseEmitter.send("Cannot run agent from state: " + this.state);
                    sseEmitter.complete();
                    return;
                }
                if (StringUtils.isBlank(userPrompt)) {
                    sseEmitter.send("Cannot run agent with empty user prompt");
                    sseEmitter.complete();
                    return;
                }
            } catch (Exception e) {
                sseEmitter.completeWithError(e);
            }
            //2.执行代理逻辑，更新状态
            this.state = AgentState.RUNNING;
            //3.记录上下文（含用户的输入信息）
            messageList.add(new UserMessage(userPrompt));
            ArrayList<Object> results = new ArrayList<>();
            try {
                //执行循环
                for (int i = 0; i < maxSteps && state != AgentState.FINISHED; i++) {
                    int stepNumber = i + 1;
                    currentStep = stepNumber;
                    log.info("Executing step {} of {}", stepNumber, maxSteps);
                    //执行步骤
                    String stepResult = step();
                    //记录结果
                    String result = "Step: " + currentStep + ": " + stepResult;
                    results.add(stepResult);
                    //发送see消息
                    sseEmitter.send(result);
                }
                if (currentStep >= maxSteps) {
                    state = AgentState.FINISHED;
                    results.add("Terminated: Reached max steps("+maxSteps+")");
                    sseEmitter.send("Terminated: Reached max steps("+maxSteps+")");
                }
                sseEmitter.complete();
            }catch (Exception e){
                state = AgentState.FINISHED;
                log.error("Error running agent", e);
                try {
                    sseEmitter.send("Error running agent: " + e.getMessage());
                    sseEmitter.complete();
                } catch (IOException ex) {
                    sseEmitter.completeWithError(ex);
                }
            }finally {
                //释放资源
                this.cleanUp();
            }
        });
        //设置超时回调
        sseEmitter.onTimeout(()-> {
            this.state = AgentState.ERROR;
            this.cleanUp();
            log.warn("Timeout running agent");
        });
        //返回sseEmitter
        sseEmitter.onCompletion(()-> {
            if (this.state == AgentState.RUNNING) {
                this.state = AgentState.FINISHED;
            }
            this.cleanUp();
            log.info("SSE connection completed");
        });
        return sseEmitter;
    }

    protected void cleanUp(){
        //可以让子类来重写此方法来·释放资源
    }
    /**
     * 定义单个步骤的逻辑
     * @return 执行解果
     */
    public abstract String step();
}
